﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using Enter.Common.Helper;
using System.Security.Cryptography;
using System.Reflection;

namespace Enter.Common.statics
{
	/// <summary>
	/// 自定义key生成器
	/// </summary>
	public class CustomKey
	{

		/// <summary>
		/// 根据命名空间，调用方法以及参数生成key
		/// 调用 Build(MethodInfo.GetCurrentMethod(), new object[] { 参数 });
		/// </summary>
		/// <returns>key</returns>
		public static string Build(MethodBase moveMethod, params object[] objlist)
		{
			StringBuilder sb = new StringBuilder();
			sb.Append(moveMethod.DeclaringType.FullName);
			sb.Append(".");
			sb.Append(moveMethod.Name);
			if (objlist != null)
			{
				foreach (object obj in objlist)
				{
					sb.Append(".");
					sb.Append(BinarySaveString(obj));
				}
			}
			string key = string.Empty;
			key = SecurityHelper.MD5Encrypt(sb.ToString());
			return key;
		}

		private static string BinarySaveString(object obj)
		{
			if (obj != null)
			{
				Type ty = obj.GetType();
				Type ty1 = ty.BaseType;
				if (ty1.Name == "ValueType")
				{
					return obj.ToString();
				}
				else
				{
					if ((ty.Name == "String") || (ty.Name == "StringBuilder"))
					{
						return obj.ToString();
					}
					else
					{
						MemoryStream outputStream = new MemoryStream();
						new BinaryFormatter().Serialize(outputStream, obj);
						outputStream.Position = 0L;
						Byte[] byte1 = outputStream.GetBuffer();
						return Convert.ToBase64String(byte1);
					}
				}
			}
			else
			{
				return "";
			}


		}
	}
}
